<template>
	<view class="good-list" :style="{paddingTop: top+'px'}">
		<scroll-view refresher-enabled :style="{height:`${windowHeight-top}px`,position:'relative'}" scroll-y :lower-threshold="80" show-scrollbar
			@refresherrefresh="refresherrefresh" @scrolltolower="scrollBottom" @scroll="handleScroll" :refresher-triggered="triggered" @refresherrestore="refresherrestore">
			<view :style="[customStyle]" style="padding-bottom: 30rpx;">
				<view v-for="(itemList,pageIndex) in list" :key="pageIndex" :id="'wrp_'+pageIndex">
					<view v-if="itemList.length > 0">
						<view v-for="(item,index) in itemList" :data="item" :index="index" :key="index">
							<view @click="itemClick(item)">
								<slot :data="item" :index="index" />
							</view>
						</view>
					</view>
					<!-- 空白占位 -->
					<view v-else-if="itemList.height" :style="'height:'+ itemList.height+'px'" class="seat">
						数据正在加载中...
					</view>
				</view>
				<u-empty v-if="list.length==0&&status=='nomore'" mode="list" margin-top="500"></u-empty>
				<u-loadmore v-else :status="status" style="height: 30rpx;margin-top: 80rpx;" :load-text="loadText" />
			</view>

		</scroll-view>

	</view>
</template>

<script>
	const throttle = (fn, delay) => {
		var startTime = new Date();
		return function() {
			var context = this;
			var args = arguments;
			var endTime = new Date();
			var resTime = endTime - startTime;
			//判断大于等于我们给的时间采取执行函数;
			if (resTime >= delay) {
				fn.apply(context, args);
				//执行完函数之后重置初始时间，等于最后一次触发的时间
				startTime = endTime;
			}
		}
	}
	let that
	import {
		mapGetters,
		mapMutations
	} from 'vuex'
	export default {
		computed: {
			...mapGetters(['userInfo', 'api']),
		},
		props: {
			top:{
				type: [Number],
				default () {
					return 0
				}
			},
			windowHeight: { //当前滚动区域的高度 默认是屏幕高度
				type: [Number],
				default () {
					return uni.getSystemInfoSync().windowHeight
				}
			},
			customStyle: {
				type: [Object],
				default () {
					return {}
				}
			},
			status: { //加载状态
				type: [String],
				default () {
					return 'loadmore'
				}
			},
		},
		data() {
			return {
				triggered:false,
				loadText: {
					loadmore: '轻轻上拉',
					loading: '努力加载中',
					nomore: '实在没有了'
				},

				list: [],
				wholePageIndex: 0, //已加载几页数据
				wholeVideoList: [], //用来装所有屏的数据
				currentRenderIndex: 0, //当前正在渲染哪一页
				index: 0,
				pageHeightArr: [], //用来装每一屏的高度
			}
		},
		mounted() {
			that = this
		},
		methods: {
			//复位
			refresherrestore(){
				this.triggered = 'restore'; // 需要重置
			},
			reset() {
				this.list = []
				this.wholePageIndex = 0
				this.wholeVideoList = []
				this.currentRenderIndex = 0
				this.index = 0
				this.pageHeightArr = []
				setTimeout(() => {
					this.triggered = false;
				}, 500)
				
			},
			//下拉刷新
			refresherrefresh() {
				this.$emit('refresherrefresh')
				this.triggered = true;
			},
			//滚动到底部
			scrollBottom() {
				this.$emit('scrollBottom')
			},
			itemClick(item) {
				this.$emit('itemClick', item)
			},
			//设置当前屏幕数据高度
			setHeight() {
				const wholePageIndex = this.wholePageIndex;
				const query = uni.createSelectorQuery().in(this);
				this.$nextTick(() => {
					setTimeout(() => {
						const query = uni.createSelectorQuery().in(this);
						query.select(`#wrp_${wholePageIndex}`).boundingClientRect(data => {
							if (data && data.height) {
								//保存当前数据的高度
								that.pageHeightArr[wholePageIndex] = data.height;
							}
							//console.log('当前数据的高度' + wholePageIndex, data.height, that.pageHeightArr);
						}).exec();
					}, 80)
				})
			},
			//初始化时设置参数 //为二维数组，每个item表示一屏数据
			setListData(arr) {
				//第一页数据
				if (this.wholePageIndex == 0) {
					//this.list为要渲染的数据，设置第一屏数据
					this.$set(this.list, this.wholePageIndex, arr)
					//后台请求的所有数据
					this.wholeVideoList[this.wholePageIndex] = arr;
					//设置当前屏幕数据高度
					this.setHeight();
					//设置第二页
					this.wholePageIndex++
					return
				}
				// 当前第二页数据进来
				const wholePageIndex = this.wholePageIndex;
				//说明已经滚动到第二屏
				this.currentRenderIndex = wholePageIndex;
				//设置第二页数据
				this.wholeVideoList[wholePageIndex] = arr;
				let tempList = new Array(wholePageIndex + 1).fill(0);
				//console.log(`---------------第${wholePageIndex}批数据来了--------------------------`);
				//当新的数据过来并且超过3页 把前面的数据清空留下后面两页数据
				if (wholePageIndex > 2) {
					tempList.forEach((item, index) => {
						if (index < tempList.length - 2) {
							tempList[index] = {
								height: this.pageHeightArr[index]
							};
						} else {
							tempList[index] = this.wholeVideoList[index];
						}

					})
					this.list = tempList;
				} else {
					this.$set(this.list, this.wholePageIndex, arr)
				}
				this.setHeight();
				this.wholePageIndex++
			},
			handleScroll: throttle(function(e) {
				const realScrollTop = e.detail.scrollTop;
				// 滚动的时候需要实时去计算当然应该在哪一屏幕
				let tempScrollTop = 0;
				const wholePageIndex = this.wholePageIndex;
				for (var i = 0; i < this.pageHeightArr.length; i++) {
					tempScrollTop = tempScrollTop + this.pageHeightArr[i];
					if (tempScrollTop > realScrollTop + this.windowHeight) {
						//console.log('当前滚动在那一屏' + i);
						this.computedCurrentIndex = i;
						break;
					}
				}
				const currentRenderIndex = this.currentRenderIndex;
				if (this.computedCurrentIndex !== currentRenderIndex) {
					// 这里给不渲染的元素占位
					let tempList = new Array(wholePageIndex).fill(0);
					// 只保留当前屏幕的前后两屏的数据，其他占位
					tempList.forEach((item, index) => {
						if (this.computedCurrentIndex - 1 <= index && index <= this.computedCurrentIndex +
							1) {
							if (that.wholeVideoList[index]) {
								tempList[index] = that.wholeVideoList[index];
							}
						} else {
							//console.log('其他地方占位', that.pageHeightArr[index], index);
							if (that.pageHeightArr[index]) {
								tempList[index] = {
									height: that.pageHeightArr[index]
								};
							}

						}
					})

					this.currentRenderIndex = this.computedCurrentIndex;
					// 渲染第一屏的时候，如果之前这里有看到这里，并且showVideoIcon，那么需要重新绑定一次。
					this.list = tempList
				}
			}, 500)

		}

	}
</script>

<style lang="scss">
	.good-list{background-color: #fff;}
	.seat {
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>
